package org.letva.toink.persistence;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

import com.google.inject.Provider;

public class SessionFactoryProvider implements Provider<SessionFactory> {

	private final static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";

	private static SessionFactory sessionFactory = null;

	@Override
	public SessionFactory get() {
		return getSessionFactory();
	}

	public synchronized SessionFactory buildSessionFactory() {
		if (sessionFactory != null) {
			throw new RuntimeException("Duplicate session factory creation!");
		}

		try {
			Configuration configuration = new AnnotationConfiguration()
					.configure(CONFIG_FILE_LOCATION);
			sessionFactory = configuration.buildSessionFactory();

			return sessionFactory;
		} catch (HibernateException ex) {
			throw new RuntimeException("buildSessionFactory failed!", ex);
		}
	}

	private SessionFactory getSessionFactory() {
		if (sessionFactory != null) {
			return sessionFactory;
		}
		return buildSessionFactory();
	}
}
